package com.zygh.lz.controller.pc.role;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zygh.lz.entity.Staff;
import com.zygh.lz.entity.app.RolePermission;
import com.zygh.lz.entity.role.SysRole;
import com.zygh.lz.entity.role.SysRoleMenu;
import com.zygh.lz.entity.role.SysUserRole;
import com.zygh.lz.service.AccountService;
import com.zygh.lz.service.SectionService;
import com.zygh.lz.service.StaffService;
import com.zygh.lz.service.role.RolePermissionServiceImpl;
import com.zygh.lz.service.role.SysRoleMenuServiceImpl;
import com.zygh.lz.service.role.SysRoleServiceImpl;
import com.zygh.lz.service.role.SysUserRoleServiceImpl;
import com.zygh.lz.stapprove.ResultUtil;
import com.zygh.lz.stapprove.SysPcLog;
import com.zygh.lz.vo.ResultBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ms151
 */
@Api(tags = "角色管理")
@RestController
@RequestMapping("/sys/role")
public class SysRoleController {

    @Resource
    private SysRoleServiceImpl sysRoleService;
    @Resource
    private SysRoleMenuServiceImpl sysRoleMenuService;
    @Resource
    private SysUserRoleServiceImpl sysUserRoleService;
    @Resource
    private StaffService staffService;
    @Resource
    private RolePermissionServiceImpl rolePermissionService;
    @Resource
    private SectionService sectionService;
    @Resource
    private AccountService accountService;
    @ApiOperation("根据角色id获取角色")
    //@PreAuthorize("hasAuthority('sys:role:list')")
    @GetMapping("/info/{id}")
    public ResultBean info(@PathVariable("id") Long id) {

        SysRole sysRole = sysRoleService.getById(id);

        // 获取角色相关联的菜单id
        List<SysRoleMenu> roleMenus = sysRoleMenuService.list(new QueryWrapper<SysRoleMenu>().eq("role_id", id));
        List<Long> menuIds = roleMenus.stream().map(p -> p.getMenuId()).collect(Collectors.toList());

        sysRole.setMenuIds(menuIds);
        return ResultUtil.setOK("查询成功", sysRole);
    }

    @ApiOperation("获取角色列表")
    //@PreAuthorize("hasAuthority('sys:role:list')")
    @GetMapping("/list")
    public ResultBean list(String name,
                           @RequestParam(defaultValue = "1") int pageNum,
                           @RequestParam(defaultValue = "10") int pageSize) {
        Page<SysRole> pageData = sysRoleService.page(getPage(pageNum, pageSize),
                new QueryWrapper<SysRole>()
                        .like(StrUtil.isNotBlank(name), "name", name)
        );

        return ResultUtil.setOK("查询成功", pageData);
    }

    Page getPage(int current, int size) {
        return new Page(current, size);
    }


    @ApiOperation("获取角色列表不分页")
    @GetMapping("/findListAll")
    public ResultBean findListAll() {
        return ResultUtil.setOK("查询成功", sysRoleService.list());
    }

    @ApiOperation("根据用户id获取角色id")
    @GetMapping("/findRoleById")
    public ResultBean findRoleById(int id) {
        return ResultUtil.setOK("查询成功", sysUserRoleService.getOne(new QueryWrapper<SysUserRole>().eq("user_id", id)));
    }


    @ApiOperation("新增角色")
    @PostMapping("/save")
    @SysPcLog(module = "新增角色信息",operation = "新增")
    //@PreAuthorize("hasAuthority('sys:role:save')")
    public ResultBean save(@Validated @RequestBody SysRole sysRole) {
        sysRole.setCode(IdUtil.fastUUID());
        sysRole.setCreated(new Date());
        return sysRoleService.save(sysRole) ? ResultUtil.setOK("新增成功", null) : ResultUtil.setError(500, "新增失败", null);


    }

    @ApiOperation("修改角色")
    @PostMapping("/update")
    @SysPcLog(module = "修改角色信息",operation = "修改")
    // @PreAuthorize("hasAuthority('sys:role:update')")
    public ResultBean update(@Validated @RequestBody SysRole sysRole) {

        sysRole.setUpdated(new Date());
        return sysRoleService.updateById(sysRole) ? ResultUtil.setOK("修改成功", null) : ResultUtil.setError(500, "修改失败", null);

    }


    @ApiOperation("删除角色")
    @PostMapping("/delete")
    @SysPcLog(module = "删除角色信息",operation = "删除")
    // @PreAuthorize("hasAuthority('sys:role:delete')")
    @Transactional
    public ResultBean info(@RequestBody Long[] ids) {

        List<Map<String,Object>> da = accountService.selByRoles(ids);
        if(Objects.nonNull(da)&& CollUtil.isNotEmpty(da)){
            return ResultUtil.setError(500,"该权限下存在用户", null);
        }
        boolean b = sysRoleService.removeByIds(Arrays.asList(ids));
        // 删除中间表
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("role_id", ids));
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().in("role_id", ids));

        if (b) {
            return ResultUtil.setOK("删除成功", null);
        }
        return ResultUtil.setError(500, "删除失败", null);
    }


    @ApiOperation("角色分配权限")
    @Transactional
    @PostMapping("/perm/{roleId}")
    @SysPcLog(module = "角色分配权限",operation = "角色分配权限")
    //@PreAuthorize("hasAuthority('sys:role:perm')")
    public ResultBean info(@PathVariable("roleId") Long roleId, @RequestBody Long[] menuIds) {
        SysRole byId = sysRoleService.getById(roleId);
        int signboard = byId.getSignboard();
        //PC端角色分配菜单
        if (signboard == 1) {
            List<SysRoleMenu> sysRoleMenus = new ArrayList<>();

            Arrays.stream(menuIds).forEach(menuId -> {
                SysRoleMenu roleMenu = new SysRoleMenu();
                roleMenu.setMenuId(menuId);
                roleMenu.setRoleId(roleId);

                sysRoleMenus.add(roleMenu);
            });

            // 先删除原来的记录，再保存新的
            sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id", roleId));
            sysRoleMenuService.saveBatch(sysRoleMenus);
            return ResultUtil.setOK("分配成功", null);
        }

        //APP角色分配菜单
        if (signboard == 2) {
            List<RolePermission> sysRoleMenus = new ArrayList<>();
            Arrays.stream(menuIds).forEach(menuId -> {
                RolePermission roleMenu = new RolePermission();
                roleMenu.setPermissionId(menuId);
                roleMenu.setRoleId(roleId);
                sysRoleMenus.add(roleMenu);
            });

            // 先删除原来的记录，再保存新的
            rolePermissionService.remove(new QueryWrapper<RolePermission>().eq("role_id", roleId));
            rolePermissionService.saveBatch(sysRoleMenus);
            return ResultUtil.setOK("分配成功", null);
        }


        return ResultUtil.setError(500, "请先选择用户类型", null);

    }

    @Transactional
    @ApiOperation("用户角色分配")
    @PostMapping("/role/{userId}")
    @SysPcLog(module = "用户角色分配",operation = "用户角色分配")
    //@PreAuthorize("hasAuthority('sys:user:role')")
    public ResultBean rolePerm(@PathVariable("userId") Long userId, @RequestBody Long[] roleIds) {

        SysRole byId = sysRoleService.getById(roleIds[0]);
        int signboard = byId.getSignboard();

        //PC端用户分配角色
        if (signboard == 1) {
            List<SysUserRole> userRoles = new ArrayList<>();

            Arrays.stream(roleIds).forEach(r -> {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(r);
                sysUserRole.setUserId(userId);
                userRoles.add(sysUserRole);
            });

            sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", userId));
            sysUserRoleService.saveBatch(userRoles);
            return ResultUtil.setOK("分配成功", null);
        }

        //APP角色
        if (signboard == 2) {
            //Staff sysStaffId = staffService.getOne(new QueryWrapper<Staff>().eq("sysStaffId", userId));
            Staff sysStaffId = staffService.getById(userId);
            sysStaffId.setAppRoleId(roleIds[0].intValue());
            staffService.updateById(sysStaffId);
            return ResultUtil.setOK("分配成功", null);
        }

        return ResultUtil.setError(500, "请先选择用户类型", null);

    }

    @GetMapping("role/by/section")
    public ResultBean roleBySection(String sectionId) {
        List<SysRole> list = sysRoleService.list(Wrappers.<SysRole>lambdaQuery().eq(SysRole::getSectionId, sectionId));
        return ResultUtil.setOK("查询成功", list);
    }


    @GetMapping("/tree")
    public ResultBean tree(Integer id) {
        return sectionService.getSectionRoleTree(id);
    }

    @GetMapping("/man")
    public ResultBean man(Integer sysSectionId, Integer id,
                          @RequestParam(defaultValue = "1") Integer pageNum,
                          @RequestParam(defaultValue = "10") Integer pageSize) {
        return sectionService.man(sysSectionId, id, pageNum, pageSize);
    }

    @PostMapping("/update/man")
    public ResultBean updateMan(@RequestBody Staff staff) {
        return sectionService.updateMan(staff);
    }

    @PostMapping("/man/delete")
    public ResultBean delete(@RequestBody List<Integer> staff) {
        return sectionService.delete(staff);
    }
}
